package com.example.bookstore.controller;

import com.example.bookstore.entity.*;
import com.example.bookstore.service.BookService;
import com.example.bookstore.service.OrderService;
import com.example.bookstore.service.PeopleService;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class PeopleController {
    @Resource
    private PeopleService peopleService;

    @Resource
    private BookService bookService;

    @Resource
    private OrderService orderService;




    /**
     * 登录
     * @param username
     * @param password
     * @param remember
     * @param model
     * @param session
     * @param response
     * @return
     */
    @RequestMapping("/login")
    public String Login(String username, String password, String remember, Model model, HttpSession session, HttpServletResponse response){

        People people = peopleService.Login(username, password);
        //登录成功
        if (people!=null){
            if("1".equals(remember)){
                //创建cookie对象
                Cookie c_username=new Cookie("username",username);
                Cookie c_password=new Cookie("password",password);
                //设置cookie存活时间
                c_username.setMaxAge(60*60*24);
                c_password.setMaxAge(60*60*24);
                //发送cookie
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            session.setAttribute("SESSION_USERNAME",username);
            session.setAttribute("SESSION_ISLOGIN",true);
            Integer id = people.getId();
            session.setAttribute("SESSION_USERID",id);
            Integer level = people.getLevel();
            if (level==1){
                session.setAttribute("SESSION_LEVEL",true);
            }else {
                session.setAttribute("SESSION_LEVEL",false);
            }
            return "/findAll";
        }
        //登录失败
        model.addAttribute("login_msg","用户名或密码错误");
        return "/pages/login.jsp";
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("SESSION_LEVEL");
        session.removeAttribute("SESSION_ISLOGIN");
        session.removeAttribute("SESSION_USERNAME");
        session.removeAttribute("SESSION_USERID");
        return "redirect:/findAll";
    }


    /**
     * 注册
     * @param username
     * @param password
     * @param checkCode
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/register")
    public String Register(String username, String password, String checkCode, Model model,HttpSession session){
        //从session获取程序生成的验证码
        String checkCodeGen = (String)session.getAttribute("checkCodeGen");
        System.out.println(checkCodeGen);
        //对比验证码
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){
            model.addAttribute("register_msg","验证码输入错误");
            return "/pages/register.jsp";
        }

        // 用户名必须为6-16个字母或数字，不能包含特殊字符，不能为空
        String regex = "^[a-zA-Z0-9]{6,16}$";

        if (!(username.matches(regex) && !username.contains(" "))){
            model.addAttribute("register_msg","用户名格式错误");
            return "/pages/register.jsp";
        }
        if (!(password.matches(regex) && !password.contains(" "))){
            model.addAttribute("register_msg","密码格式错误");
            return "/pages/register.jsp";
        }

        People people = peopleService.findByUserName(username);
        if (people!=null){
            //注册失败
            model.addAttribute("register_msg","用户名已存在");
            return "/pages/register.jsp";
        }
        Integer row = peopleService.Register(username, password);
        //注册成功
        if (row!=0){
            model.addAttribute("register_msg","注册成功,请登录");
            return "/pages/login.jsp";
        }
        //注册失败
        model.addAttribute("register_msg","注册失败");
        return "/pages/register.jsp";
    }


    /**
     * 查询全部图书和分类
     * @param model
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<Book> list = bookService.findAll();
        List<Category> cList = bookService.findAllCategory();
        model.addAttribute("list",list);
        model.addAttribute("cList",cList);
        return "/pages/main.jsp";
    }


    /**
     * 查询详细信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/getDetail")
    public String getDetail(Integer id,Model model){
        Book book = bookService.findById(id);
        model.addAttribute("book",book);
        return "/pages/detail.jsp";
    }


    /**
     * 根据分类id查询图书
     * @param cid
     * @param model
     * @return
     */
    @RequestMapping("/findByCategoryId")
    public String findByCategoryId(Integer cid,Model model){
        List<Book> list = bookService.findByCategoryId(cid);
        List<Category> cList = bookService.findAllCategory();
        model.addAttribute("list",list);
        model.addAttribute("cList",cList);
        return "/pages/main.jsp";
    }


    /**
     * 根据关键词查找图书
     * @param bookName
     * @param model
     * @return
     */
    @RequestMapping("/findByKeyWord")
    public String findByKeyWord(String bookName,Model model){
        List<Book> list = bookService.findByKeyWord(bookName);
        List<Category> cList = bookService.findAllCategory();
        model.addAttribute("list",list);
        model.addAttribute("cList",cList);
        return "/pages/main.jsp";
    }



    @RequestMapping("/createOrder")
    public String createOrder(HttpSession session,Model model){

        //获取需要生成订单所需要的信息
        Integer id = (Integer) session.getAttribute("SESSION_USERID");
        String userName = (String) session.getAttribute("SESSION_USERNAME");
        List<ShopCart> list = peopleService.queryShopcart(id);
        Address address = peopleService.findAddressByUserId(id);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);

        Ordered order = new Ordered(null,id,userName,address.getDetail(),address.getPhone(),format,0);

        System.out.println(order);
        //Order(id=0, userId=1, address=河南省安阳市安阳师范学院, phone=13814381438, date=Tue Nov 21 23:21:58 CST 2023, status=0)

        //生成一个主订单
        int orderId = orderService.createOrder(order);

        //生成多个存放商品信息的link订单
        OrderLink orderLink =new OrderLink();

        for (ShopCart shopCart:list){
            orderLink.setOrderId(orderId);
            orderLink.setBookId(shopCart.getBookId());
            orderLink.setBookImage(shopCart.getImage());
            orderLink.setBookName(shopCart.getName());
            orderLink.setBookPrice(shopCart.getPrice());
            orderLink.setBookNumber(shopCart.getNumber());

            orderService.createOrderLink(orderLink);
        }

        //生成完毕，清空购物车
        peopleService.cleanShopCart(id);

        return "redirect:/user/queryShopCart";

    }


    /**
     * 查询订单
     * @return
     */
    @RequestMapping("/queryMyOrder")
    public String queryMyOrder(Model model,HttpSession session){

        Integer uid = (Integer) session.getAttribute("SESSION_USERID");
        Ordered ordered = orderService.queryMyOrdered(uid);

        model.addAttribute("ordered",ordered);

        Integer oid = ordered.getId();

        List<OrderLink> links = orderService.findOrderLinks(oid);

        model.addAttribute("list",links);


        return "/pages/myordered.jsp";
    }



}
